import {
  EffectComposer, 
  RenderPass, 
  UnrealBloomPass, 
  ShaderPass, 
  GlitchPass, 
  FXAAShader // 利用 亮度边缘检测，抗锯齿
 } from 'three/addons'

import { Canvas, useFrame, useLoader, useThree } from '@react-three/fiber'
import React, { Suspense, useEffect, useMemo, useRef, useState } from 'react'

export function PostEffect({isGlitch = false, children, isFXAA = false, isGray = false}) {
  const { scene, camera, gl } = useThree()

  const composer = useRef()

  const GrayShader = {
    uniforms: {
      'tDiffuse': { value: null }
    },
    vertexShader: `
      varying vec2 vUv;
      void main() {
        vUv = uv;
        gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
      }
    `,
    fragmentShader: `
      uniform sampler2D tDiffuse;
      varying vec2 vUv;
      #include <common>
      void main() {
        //采集纹素
        vec4 tColor = texture2D( tDiffuse, vUv );
        //计算RGB三个分量光能量之和，也就是亮度
        float luminance = 0.299*tColor.r+0.587*tColor.g+0.114*tColor.b;
        // 逐片元赋值，RGB相同均为亮度值，用黑白两色表达图片的明暗变化
        gl_FragColor = vec4(luminance,luminance,luminance,1);
      }
    `
  };

  const GrayShaderPass = isGray && new ShaderPass(GrayShader);
  const FXAAShaderPass = isFXAA && new ShaderPass(FXAAShader);

  useEffect(() => {
    composer.current = new EffectComposer(gl)
    composer.current.addPass(new RenderPass(scene, camera))
    // composer.current.addPass(new UnrealBloomPass())
    isGray && composer.current.addPass(GrayShaderPass);

    isFXAA && composer.current.addPass(FXAAShaderPass);
    isGlitch && composer.current.addPass(new GlitchPass());
  }, [scene, camera, gl])

  useFrame((state, delta) => {
    // console.log('composer.current', composer.current)
    composer.current?.render?.()
  }, 2)

  return (
    <Suspense fallback={null}>
      {children}
    </Suspense>
  )
}